package com.lujianing.test;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.jpedal.PdfDecoder;
import org.jpedal.exception.PdfException;
import org.jpedal.fonts.FontMappings;

import com.itextpdf.text.DocumentException;
 
/**
 * Created by lujianing on 2017/5/7.
 */
public class JavaToPdfImgHtmlFreeMarker {
 
    private static final String DEST = "target/HelloWorld_CN_HTML_FREEMARKER_FS_IMG.png";
    private static final String IMG_EXT = "png";
 
 
    public static void main(String[] args) throws IOException, DocumentException, com.lowagie.text.DocumentException {
        
        FileInputStream  fis = new FileInputStream("D:/workspace/jxyh/java_pdf_demo/target/HelloWorld_CN_HTML_FREEMARKER_FS.pdf");
        ByteArrayOutputStream bos = new ByteArrayOutputStream();  
        byte[] b = new byte[1024];  
        int n;  
        while ((n = fis.read(b)) != -1)  
        {  	
            bos.write(b, 0, n);  
        }  
        fis.close();  
        bos.close();  
        
        ByteArrayOutputStream imgSteam = JavaToPdfImgHtmlFreeMarker.pdfToImg(bos.toByteArray(),2,1,IMG_EXT);
 
        FileOutputStream fileStream = new FileOutputStream(new File(DEST));
        fileStream.write(imgSteam.toByteArray());
        fileStream.close();
 
    }
 
    /**
     * 根据pdf二进制文件 生成图片文件
     *
     * @param bytes   pdf二进制
     * @param scaling 清晰度
     * @param pageNum 页数
     */
    public static ByteArrayOutputStream pdfToImg(byte[] bytes, float scaling, int pageNum,String formatName) {
        //推荐的方法打开PdfDecoder
        PdfDecoder pdfDecoder = new PdfDecoder(true);
        FontMappings.setFontReplacements();
        //修改图片的清晰度
        pdfDecoder.scaling = scaling;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            //打开pdf文件，生成PdfDecoder对象
            pdfDecoder.openPdfArray(bytes); //bytes is byte[] array with PDF
            //获取第pageNum页的pdf
            BufferedImage img = pdfDecoder.getPageAsImage(pageNum);
 
            ImageIO.write(img, formatName, out);
        } catch (PdfException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
 
        return out;
    }
}